package com.briup.jdk8.day02;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;

/**
 * Function
 * 输入任意类型的参数，得到任意类型的参数
 * 映射转换
 */
public class Test3 {
    // 使用者视角
    public static void main(String[] args) {
        // 准备一个字符串
        String s = "a-b-c-a-b-c";
        // run方法：将字符串分割成字符串的数组
        Function<String,String[]> f1 = a -> a.split("-");
        // String[] strings = run(s, f1);
        // 将strings 去重
        Function<String[],String[]> f2 = a -> {
            Set<String> set = new LinkedHashSet<>(Arrays.asList(a));

            return set.toArray(new String[0]);
        };
        String[] result = run(s, f2.compose(f1)/* => f1.andThen(f2) */);
        System.out.println(Arrays.toString(result));

        // 实际应用
        Map<Integer,String> map = new HashMap<>();
        map.put(1,"tom");
        map.put(2,"jerry");
        map.put(3,null);
        map.put(4,null);
        // 下面的代码等价于 int i = 1; i++;
        AtomicInteger i = new AtomicInteger(1);
        Function<Integer,String> f = a->"default_"+(i.getAndIncrement());
        map.computeIfAbsent(5,f);
        map.computeIfAbsent(6,f);
        map.forEach((k,v)-> System.out.println(k+":"+v));
    }
    // 设计者视角
    public static <T,R> R run(T t, Function<T,R> function){
        return function.apply(t);
    }
}
